package com.aiyige.page.globalsearch;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.apiengine.ModuleEngine;
import com.aiyige.model.Keyword;
import com.aiyige.model.Summary;
import com.aiyige.model.moment.entity.MajorCourse;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.moment.entity.TrainingCourse;
import com.aiyige.page.globalsearch.adapter.GroupSearchAdapter;
import com.aiyige.page.globalsearch.adapter.KeywordAssociateAdapter;
import com.aiyige.page.globalsearch.model.KeywordAssociateItem;
import com.aiyige.page.globalsearch.model.SearchGroup;
import com.aiyige.page.globalsearch.util.SearchUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.HighLightWordUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.GlobalGroupSearchPage)
public class GlobalGroupSearchPage extends AppCompatActivity {
    public static final String TAG = GlobalGroupSearchPage.class.getSimpleName();
    public static final int HANDLE_SEARCH = 1;
    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.searchGroupResultRv)
    RecyclerView searchGroupResultRv;
    @BindView(R.id.keywordAssociateRv)
    RecyclerView keywordAssociateRv;
    @BindView(R.id.keywordAssociateLayout)
    FrameLayout keywordAssociateLayout;
    @Autowired
    String searchWord;
    KeywordAssociateAdapter keywordAssociateAdapter;
    GroupSearchAdapter groupSearchAdapter;
    Handler mainHandler;
    Handler searchHandler;
    HandlerThread searchThread;
    TextWatcher searchTextWatcher;
    @BindView(R.id.inputEtClearBtn)
    ImageView inputEtClearBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_global_group_search);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        inputEt.setText(searchWord);
        searchGroupResultRv.setLayoutManager(new LinearLayoutManager(this));
        groupSearchAdapter = new GroupSearchAdapter();
        groupSearchAdapter.bindToRecyclerView(searchGroupResultRv);
        groupSearchAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                SearchGroup data = groupSearchAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.moreLayout:
                        ARouter.getInstance()
                                .build(ARouterConfig.GlobalDetailSearchPage)
                                .withInt("type", data.getTypeId())
                                .withString("searchWord", searchWord)
                                .navigation();
                        break;
                }
            }
        });
        keywordAssociateRv.setLayoutManager(new LinearLayoutManager(this));
        keywordAssociateAdapter = new KeywordAssociateAdapter();
        keywordAssociateAdapter.bindToRecyclerView(keywordAssociateRv);
        keywordAssociateAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                searchWord = keywordAssociateAdapter.getItem(position).getKeyword();
                inputEt.removeTextChangedListener(searchTextWatcher);
                inputEt.setText(searchWord);
                inputEt.addTextChangedListener(searchTextWatcher);
                hideKeywordAssociate();
                requestData();
            }
        });
        searchTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    inputEtClearBtn.setVisibility(View.INVISIBLE);
                    hideKeywordAssociate();
                    keywordAssociateAdapter.setNewData(null);
                } else {
                    inputEtClearBtn.setVisibility(View.VISIBLE);
                    showKeywordAssociate();
                    doSearch(s.toString());
                }
            }
        };
        inputEt.addTextChangedListener(searchTextWatcher);
        inputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(v.getText().toString())) {
                        searchWord = v.getText().toString();
                        hideKeywordAssociate();
                        KeyboardUtil.hideKeyboard(v.getContext(), v);
                        requestData();
                        return true;
                    }
                }
                return false;
            }
        });
        mainHandler = new Handler(Looper.getMainLooper());
        searchThread = new HandlerThread(TAG + "SearchThread");
        searchThread.start();
        searchHandler = new Handler(searchThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLE_SEARCH:
                        String searchStr = (String) msg.obj;
                        final List<KeywordAssociateItem> resultList = new LinkedList<>();
                        if (!TextUtils.isEmpty(searchStr)) {
                            try {
                                Response<ResponseBody> response = ApiManager.getService().searchKeywordAssociate(searchStr).execute();
                                if (response.code() != ResponseCode.OK) {
                                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                }
                                String json = RetrofitUtil.getResponseBodyAsString(response);
                                List<Keyword> keywordList = JSON.parseArray(json, Keyword.class);
                                for (Keyword keyword : keywordList) {
                                    resultList.add(KeywordAssociateItem.newBuilder()
                                            .keyword(keyword.getKeyword())
                                            .build());
                                }
                            } catch (Exception e) {

                            }
                        }
                        mainHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                keywordAssociateAdapter.setNewData(resultList);
                            }
                        });
                        break;
                }
            }
        };
        inputEt.setFilters(new InputFilter[]{new InputNumFilter(30, false)});
        requestData();
    }

    private void doSearch(String searchStr) {
        Message msg = Message.obtain();
        msg.what = HANDLE_SEARCH;
        msg.obj = searchStr;
        searchHandler.removeMessages(HANDLE_SEARCH);
        searchHandler.sendMessage(msg);
    }

    public void requestData() {
        new RequestDataTask().execute();
    }

    @OnClick({R.id.cancelBtn, R.id.inputEtClearBtn})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.cancelBtn:
                finish();
                break;
            case R.id.inputEtClearBtn:
                inputEt.setText("");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        searchThread.quit();
        super.onDestroy();
    }

    public void showKeywordAssociate() {
        keywordAssociateLayout.setVisibility(View.VISIBLE);
    }

    public void hideKeywordAssociate() {
        keywordAssociateLayout.setVisibility(View.INVISIBLE);
    }


    public class RequestDataTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        List<SearchGroup> searchGroupList = new LinkedList<>();

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(GlobalGroupSearchPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .seachMomentSummary(ModuleEngine.SEARCH_ZONE, searchWord, 1)
                        .execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Summary summary = JSON.parseObject(json, Summary.class);

                SearchGroup dynamicSearchGroup = new SearchGroup();
                dynamicSearchGroup.setTypeId(SearchUtil.TYPE_DYNAMIC);
                dynamicSearchGroup.setName(StringUtils.getString(R.string.global_search_group_dynamic));
                dynamicSearchGroup.setHasMore(!ListUtil.isEmpty(summary.getActivity()) && summary.getActivity().size() >= SearchGroup.MAX_SAMPLE_NUM);
                dynamicSearchGroup.setSamples(new LinkedList<SearchGroup.Sample>());
                dynamicSearchGroup.setTotal(summary.getActivityCount());
                for (Moment item : summary.getActivity()) {
                    Moment moment = new Moment(item);
                    SearchGroup.Sample sample = new SearchGroup.Sample();
                    sample.setId(moment.getId());
                    sample.setCity(moment.getCityId());
                    sample.setCover(ListUtil.isEmpty(moment.getCover()) ? "" : moment.getCover().get(0));
                    sample.setCategoryId(moment.getCategoryId());
                    sample.setOwner(moment.getCreatorBackup().getName());
                    sample.setOwnerAvatar(moment.getCreatorBackup().getAvatar());
                    sample.setOwnerId(moment.getCreator());
                    sample.setOwnerLevel(moment.getCreatorBackup().getLevel());
                    sample.setTitle(HighLightWordUtil.highLight(moment.getTitle(), searchWord));
                    switch (moment.getSubject()) {
                        case Moment.SUBJECT_VIDEO:
                            sample.setType(SearchUtil.TYPE_VIDEO);
                            sample.setDurationTotal(moment.getMediaSummary().getDuration());
                            sample.setStages(moment.getMediaSummary().getCount());
                            break;
                        case Moment.SUBJECT_PHOTO:
                            sample.setType(SearchUtil.TYPE_PHOTO);
                            sample.setStages(moment.getMediaSummary().getCount());
                            break;
                        case Moment.SUBJECT_ARTICLE:
                            sample.setType(SearchUtil.TYPE_INFO);
                            break;
                    }
                    sample.setViewCount(moment.getStatisticsBackup().getViewCount());
                    sample.setRouter(moment.getRouter());
                    dynamicSearchGroup.getSamples().add(sample);
                }
                searchGroupList.add(dynamicSearchGroup);

                SearchGroup learnVideoSearchGroup = new SearchGroup();
                learnVideoSearchGroup.setTypeId(SearchUtil.TYPE_LEARN_VIDEO);
                learnVideoSearchGroup.setName(StringUtils.getString(R.string.global_search_group_learn_video));
                learnVideoSearchGroup.setHasMore(!ListUtil.isEmpty(summary.getVideoCourse()) && summary.getVideoCourse().size() >= SearchGroup.MAX_SAMPLE_NUM);
                learnVideoSearchGroup.setSamples(new LinkedList<SearchGroup.Sample>());
                learnVideoSearchGroup.setTotal(summary.getVideoCourseCount());
                for (Moment item : summary.getVideoCourse()) {
                    Moment moment = new Moment(item);
                    SearchGroup.Sample sample = new SearchGroup.Sample();
                    sample.setId(moment.getId());
                    sample.setCity(moment.getCityId());
                    sample.setCover(ListUtil.isEmpty(moment.getCover()) ? "" : moment.getCover().get(0));
                    sample.setCategoryId(moment.getCategoryId());
                    sample.setOwner(moment.getCreatorBackup().getName());
                    sample.setOwnerAvatar(moment.getCreatorBackup().getAvatar());
                    sample.setOwnerId(moment.getCreator());
                    sample.setOwnerLevel(moment.getCreatorBackup().getLevel());
                    sample.setTitle(HighLightWordUtil.highLight(moment.getTitle(), searchWord));
                    sample.setType(SearchUtil.TYPE_LEARN_VIDEO);
                    sample.setDurationTotal(moment.getMediaSummary().getDuration());
                    sample.setStages(moment.getMediaSummary().getCount());
                    sample.setViewCount(moment.getStatisticsBackup().getViewCount());
                    sample.setRouter(moment.getRouter());
                    sample.setSellCount(moment.getStatisticsBackup().getSellCount());
                    sample.setPrice(moment.getCommodityBackup().getPrice());
                    sample.setOriginPrice(moment.getCommodityBackup().getOriginPrice());
                    learnVideoSearchGroup.getSamples().add(sample);
                }
                searchGroupList.add(learnVideoSearchGroup);

                SearchGroup majorCourseSearchGroup = new SearchGroup();
                majorCourseSearchGroup.setTypeId(SearchUtil.TYPE_MAJOR_COURSE);
                majorCourseSearchGroup.setName(StringUtils.getString(R.string.global_search_group_major_course));
                majorCourseSearchGroup.setHasMore(!ListUtil.isEmpty(summary.getMajorCourse()) && summary.getMajorCourse().size() >= SearchGroup.MAX_SAMPLE_NUM);
                majorCourseSearchGroup.setSamples(new LinkedList<SearchGroup.Sample>());
                majorCourseSearchGroup.setTotal(summary.getMajorCourseCount());
                for (Moment item : summary.getMajorCourse()) {
                    Moment moment = new Moment(item);
                    SearchGroup.Sample sample = new SearchGroup.Sample();
                    sample.setId(moment.getId());
                    sample.setCity(moment.getCityId());
                    sample.setCover(ListUtil.isEmpty(moment.getCover()) ? "" : moment.getCover().get(0));
                    sample.setCategoryId(moment.getCategoryId());
                    sample.setOwner(moment.getCreatorBackup().getName());
                    sample.setOwnerAvatar(moment.getCreatorBackup().getAvatar());
                    sample.setOwnerId(moment.getCreator());
                    sample.setOwnerLevel(moment.getCreatorBackup().getLevel());
                    sample.setTitle(HighLightWordUtil.highLight(moment.getTitle(), searchWord));
                    sample.setType(SearchUtil.TYPE_MAJOR_COURSE);
                    try {
                        MajorCourse majorCourse = JSON.parseObject(moment.getMoreBackup(), MajorCourse.class);
                        sample.setDurationTotal(majorCourse.getClassCount());
                    } catch (Exception e) {
                        sample.setDurationTotal(0);
                    }
                    sample.setStages(moment.getMediaSummary().getCount());
                    sample.setViewCount(moment.getStatisticsBackup().getViewCount());
                    sample.setRouter(moment.getRouter());
                    sample.setSellCount(moment.getStatisticsBackup().getSellCount());
                    sample.setPrice(moment.getCommodityBackup().getPrice());
                    sample.setOriginPrice(moment.getCommodityBackup().getOriginPrice());
                    majorCourseSearchGroup.getSamples().add(sample);
                }
                searchGroupList.add(majorCourseSearchGroup);

//                SearchGroup traingClassSearchGroup = new SearchGroup();
//                traingClassSearchGroup.setTypeId(SearchUtil.TYPE_TRAING_CLASS);
//                traingClassSearchGroup.setName(StringUtils.getString(R.string.global_search_group_traing_class));
//                traingClassSearchGroup.setHasMore(!ListUtil.isEmpty(summary.getTrainingCourse()) && summary.getTrainingCourse().size() >= SearchGroup.MAX_SAMPLE_NUM);
//                traingClassSearchGroup.setSamples(new LinkedList<SearchGroup.Sample>());
//                traingClassSearchGroup.setTotal(summary.getTrainingCourseCount());
//                for (Moment item : summary.getTrainingCourse()) {
//                    Moment moment = new Moment(item);
//                    SearchGroup.Sample sample = new SearchGroup.Sample();
//                    sample.setId(moment.getId());
//                    sample.setCity(moment.getCityId());
//                    sample.setCover(ListUtil.isEmpty(moment.getCover()) ? "" : moment.getCover().get(0));
//                    sample.setCategoryId(moment.getCategoryId());
//                    sample.setOwner(moment.getCreatorBackup().getName());
//                    sample.setOwnerAvatar(moment.getCreatorBackup().getAvatar());
//                    sample.setOwnerId(moment.getCreator());
//                    sample.setOwnerLevel(moment.getCreatorBackup().getLevel());
//                    sample.setTitle(HighLightWordUtil.highLight(moment.getTitle(), searchWord));
//                    sample.setType(SearchUtil.TYPE_TRAING_CLASS);
//                    try {
//                        TrainingCourse trainingCourse = JSON.parseObject(moment.getMoreBackup(), TrainingCourse.class);
//                        sample.setDurationTotal(trainingCourse.getClassCount());
//                    } catch (Exception e) {
//                        sample.setDurationTotal(0);
//                    }
//                    sample.setStages(moment.getMediaSummary().getCount());
//                    sample.setViewCount(moment.getStatisticsBackup().getViewCount());
//                    sample.setRouter(moment.getRouter());
//                    sample.setSellCount(moment.getStatisticsBackup().getSellCount());
//                    sample.setPrice(moment.getCommodityBackup().getPrice());
//                    sample.setOriginPrice(moment.getCommodityBackup().getOriginPrice());
//                    traingClassSearchGroup.getSamples().add(sample);
//                }
//                searchGroupList.add(traingClassSearchGroup);

//                SearchGroup traingCardSearchGroup = new SearchGroup();
//                traingCardSearchGroup.setTypeId(SearchUtil.TYPE_TRAING_CARD);
//                traingCardSearchGroup.setName(StringUtils.getString(R.string.global_search_group_traing_card));
//                traingCardSearchGroup.setHasMore(!ListUtil.isEmpty(summary.getTrainingCard()) && summary.getTrainingCard().size() >= SearchGroup.MAX_SAMPLE_NUM);
//                traingCardSearchGroup.setSamples(new LinkedList<SearchGroup.Sample>());
//                traingCardSearchGroup.setTotal(summary.getTraingCardCount());
//                for (Moment item : summary.getTrainingCard()) {
//                    Moment moment = new Moment(item);
//                    SearchGroup.Sample sample = new SearchGroup.Sample();
//                    sample.setId(moment.getId());
//                    sample.setCity(moment.getCityId());
//                    sample.setCover(ListUtil.isEmpty(moment.getCover()) ? "" : moment.getCover().get(0));
//                    sample.setCategoryId(moment.getCategoryId());
//                    sample.setOwner(moment.getCreatorBackup().getName());
//                    sample.setOwnerAvatar(moment.getCreatorBackup().getAvatar());
//                    sample.setOwnerId(moment.getCreator());
//                    sample.setOwnerLevel(moment.getCreatorBackup().getLevel());
//                    sample.setTitle(HighLightWordUtil.highLight(moment.getTitle(), searchWord));
//                    try {
//                        TrainingCard trainingCard = JSON.parseObject(moment.getMoreBackup(), TrainingCard.class);
//                        switch (trainingCard.getCardType()) {
//                            case Moment.TRAINING_CARD_TYPE_MEASURED_CARD:
//                                sample.setType(SearchUtil.TYPE_TRAING_CARD_COUNT_CARD);
//                                break;
//                            case Moment.TRAINING_CARD_TYPE_TIME_CARD:
//                                sample.setType(SearchUtil.TYPE_TRAING_CARD_TIME_CARD);
//                                break;
//                            case Moment.TRAINING_CARD_TYPE_RECHARGEABLE_CARD:
//                                sample.setType(SearchUtil.TYPE_TRAING_CARD_PREPAID_CARD);
//                                break;
//                        }
//                    } catch (Exception e) {
//                        sample.setType(SearchUtil.TYPE_TRAING_CARD_COUNT_CARD);
//                    }
//                    sample.setType(SearchUtil.TYPE_TRAING_CARD);
//                    sample.setStages(moment.getMediaSummary().getCount());
//                    sample.setViewCount(moment.getStatisticsBackup().getViewCount());
//                    sample.setRouter(moment.getRouter());
//                    sample.setSellCount(moment.getStatisticsBackup().getSellCount());
//                    sample.setPrice(moment.getCommodityBackup().getPrice());
//                    sample.setOriginPrice(moment.getCommodityBackup().getOriginPrice());
//                    traingCardSearchGroup.getSamples().add(sample);
//                }
//                searchGroupList.add(traingCardSearchGroup);
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                groupSearchAdapter.setNewData(searchGroupList);
            }
        }
    }
}
